import { ref, watch } from 'vue'
import { isFunction } from 'lodash-es'
import type { FP } from '../../types'

const useReadyPlugin: FP = (fetchInstance, { ready = ref(true), manual, defaultParams = [] }) => {
  watch(
    ready,
    val => {
      if (!manual && val) {
        fetchInstance.context.run(...defaultParams)
      }
    },
    { flush: 'sync' }
  )

  return {
    onBefore() {
      const readyFlag = isFunction(ready) ? ready() : ready.value
      if (!readyFlag) {
        return {
          isBreak: true
        }
      }
    }
  }
}

export default useReadyPlugin
